import java.util.PrimitiveIterator;
import java.util.PriorityQueue;

class MyTimerTask {
    private Runnable runnable;
    //绝对时间
    private long time;
    //构造方法
    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    /**
     * 进行运算
     */
    public void run() {
        runnable.run();
    }

    /**
     * 获取时间
     * @return
     */
    public long getTime() {
        return time;
    }
    public int compareTo(MyTimerTask o) {
        //return (int) (o.time - this.time);//大堆
        return (int) (this.time - o.time);//小堆
    }
}
class MyTimer {
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask> taskQueue = new PriorityQueue<>();
    //进行扫描
    public MyTimer() {
        Thread thread = new Thread(() -> {
            try {
                while(true) {
                    synchronized (locker) {
                        if(taskQueue.size() == 0) {
                            locker.wait();
                        }
                        MyTimerTask task = taskQueue.peek();
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task.getTime()) {
                            task.run();
                            taskQueue.poll();
                        }else {
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable,delay);
            taskQueue.offer(task);
            locker.notify();
        }
    }
}
public class Demo3 {
    public static void main(String[] args) {
        //实现定时器
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000 hello");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000 hello");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000 hello");
            }
        },1000);
    }
}
